package com.keyancompany.zhongbaopingtai.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.activity.TaskDetailActivity;
import com.keyancompany.zhongbaopingtai.adapter.TaskAdapter;
import com.keyancompany.zhongbaopingtai.api.TeamAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.Task;
import com.keyancompany.zhongbaopingtai.utils.T;
import com.keyancompany.zhongbaopingtai.weight.IListView;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import butterknife.OnItemClick;

import static com.keyancompany.zhongbaopingtai.Constants.TEAM_CODE;

public class MyTaskFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, IAsyncHttpResponseHandler {

    private static final String TYPE = "type";

    @Bind(R.id.list_view)
    IListView listView;

    @Bind(R.id.find_swipe_layout)
    SwipeRefreshLayout swipeLayout;

    @Bind(R.id.empty_view)
    LinearLayout mEmptyView;


    private TaskAdapter mTaskAdapter;

    int total = 1, currentPage = 1;

    private int type;
    private String teamCode;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public MyTaskFragment() {
    }

    /**
     * 我的任务 任务状态（0待办中  1 已过期  2 进行中  3 已完成）
     *
     * @param type
     * @return
     */
    public static MyTaskFragment newInstance(int type, String teamCode) {
        MyTaskFragment fragment = new MyTaskFragment();
        Bundle args = new Bundle();
        args.putInt(TYPE, type);
        args.putString(TEAM_CODE, teamCode);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_find_item;
    }

    @Override
    public void setUpViews() {
        initSwipeLayout(swipeLayout);

        initData();
    }


    private void initData() {
        type = getArguments().getInt(TYPE);
        teamCode = getArguments().getString(TEAM_CODE);

        mTaskAdapter = new TaskAdapter(context, true, null);
        listView.setAdapter(mTaskAdapter);
        listView.setStateListener(new IListView.SwipeLayoutState() {
            @Override
            public boolean isRefresh() {
                return swipeLayout.isRefreshing();
            }

            @Override
            public boolean isLastPage() {
                return total == currentPage;
            }

            @Override
            public void requestNextPage() {
                requestTask(++currentPage, false);
            }
        });

        swipeLayout.setOnRefreshListener(this);
        if (isNetvaiable()) {
            swipeLayout.post(new Thread(new Runnable() {

                @Override
                public void run() {
                    swipeLayout.setRefreshing(true);
                    onRefresh();
                }
            }));
        }
    }

    private void requestTask(int currentPage, boolean isNeedLoad) {
        if (isNetvaiable()) {
            TeamAPI.teamTaskToMe(teamCode, currentPage, type, this, isNeedLoad ? getLoading(R.string.watting_hint) : null);
        }
    }

    @OnItemClick(R.id.list_view)
    public void listItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < mTaskAdapter.getCount()) {
            Intent intent = new Intent(context, TaskDetailActivity.class);
            intent.putExtra(Constants.TASK_ID, mTaskAdapter.getItem(position).getId());
            intent.putExtra(TEAM_CODE, teamCode);
            startActivity(intent);
        }
    }

    @OnClick(R.id.empty_hint)
    public void reqeustAgain(View v) {
//        TeamAPI.teamTask(teamCode, type, currentPage, this, getLoading(-1));
        currentPage = 1;
        requestTask(currentPage, true);
    }

    @Override
    public void onRefresh() {
        currentPage = 1;
        requestTask(currentPage, false);
    }

    @Override
    public void start(int type) {

    }

    @Override
    public void success(int type, String json) {
        swipeLayout.setRefreshing(false);
        BaseModel base = JSONObject.parseObject(json, BaseModel.class);
        if (base.isSuccess()) {
            JSONObject content = JSONObject.parseObject(base.data).getJSONObject("TaskToMe");
            currentPage = content.getInteger("current");

            List<Task> list = JSONObject.parseArray(content.getString("list"), Task.class);
            if (currentPage == 1) {
                mTaskAdapter.clear();
            }
            listView.loadMoreFinish();
            if (total == currentPage) {
                listView.removeFooterView();
            }
            total = content.getInteger("total");


            if (list != null && !list.isEmpty()) {
                swipeLayout.setVisibility(View.VISIBLE);
                mEmptyView.setVisibility(View.GONE);
                mTaskAdapter.addAllAfter(list);
            } else {
                swipeLayout.setVisibility(View.GONE);
                mEmptyView.setVisibility(View.VISIBLE);
            }
        } else
            T.showShort(getActivity(), base.msg);


    }

    @Override
    public void failed(String error) {

    }

    @Override
    public void finish(int type) {

    }
}
